import sys
import sysv_ipc
import re
import time
import datetime

test_service = [
        {'check_disk': [
            {'diskOk' : 'Disk space OK - 8899052 kB free ( 39 % used)\0'},
            {'diskWarning' : 'Disk space WARNING - 6647236 kB free ( *61* % used)\0'},
            {'diskCritical' : 'Disk space CRITICAL - 6647224 kB free ( *61* % used)\0'},
            {'diskWrong' : 'sbrubles\0'}]},
        {'check_cpu': [
            {'cpuOk' : 'CPU usage (%user %system %idle) OK - 0 0 99\0'},
            {'cpuWarning' : 'CPU usage (%user %system %idle) WARNING - 0 0 *99*\0'},
            {'cpuCritical' : 'CPU usage (%user %system %idle) CRITICAL - 0 0 *99*\0'},
            {'cpuWrong' : 'sbrubles\0'}]},
        {'check_load': [
            {'loadOk' : 'Load average OK - 0 0 0\0'},
            {'loadWarning' : 'Load average WARNING - 0 0 *2*\0'},
            {'loadCritical' : 'Load average CRITICAL - 0 0 *5*\0'},
            {'loadWrong' : 'sbrubles\0'}]},
        {'check_memory': [
            {'memoryOk' : 'Memory RAM OK - 81808 kB free ( 2088564 kB used)\0'},
            {'memoryWarning' : 'Memory RAM WARNING - *185900* kB free ( 2182264 kB used)\0'},
            {'memoryCritical' : 'Memory RAM CRITICAL - *185060* kB free ( 2181424 kB used)\0'},
            {'memoryWrong' : 'sbrubles\0'}]},
        {'check_swap\0': [
            {'swapOk' : 'Swap OK - 2097144 kB total size ( 2097144 kB available space)\0'},
            {'swapWarning' : 'Swap WARNING - 2104504 kB total size ( *1996364* kB available space)\0'},
            {'swapCritical' : 'Swap CRITICAL - 2104504 kB total size ( *1996364* kB available space)\0'},
            {'swapWrong' : 'sbrubles\0'}]},
        {'check_mysql_query': [
            {'queryOk' :"QUERY OK: 'select count(*) from nagios_hosts' returned 53.000000\0"},
            {'queryWarning' : "QUERY WARNING: 'select count(*) from nagios_hosts' returned 53.000000\0"},
            {'queryCritical' : "QUERY CRITICAL: 'select count(*) from nagios_hosts' returned 53.000000\0"},
            {'queryWrong' : 'sbrubles\0'}]},
        {'check_smtp': [
            {'smtpOk' : 'SMTP OK - 0.010 sec. response time\0'},
            {'smtpWarning' : 'SMTP WARNING - 0.016 sec. response time\0'},
            {'smtpCritical' : 'SMTP CRITICAL - 0.550 sec. response time\0'},        
            {'smtpWrong' : 'sbrubles\0'}]},
        {'host': [
            {'srvvld48Ok' : 'FPING OK - srvvld48.test.com (loss=0%, rta=1.010000 ms)\0'},
            {'srvvld48Warning' : 'FPING WARNING - srvvld48.globoi.com (loss=0%, rta=0.560000 ms)\0'},
            {'srvvld48Critical' : 'FPING CRITICAL - srvvld48.test.com (loss=100% )\0'},
            {'srvvWrong' : 'sbrubles\0'}]}
    ]


def main():
  
  DAT = open("fakenagios.dat", "w")

  scale_list = [1000.0] #, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0]
 
  period = 600
  
  mq = sysv_ipc.MessageQueue(123456, flags = sysv_ipc.IPC_CREAT, mode = 0644)
  
  for scale in scale_list:
    check = True
    msg_counter = 0
    service_counter = status_counter = 0
    init_time = time.time()
    print("Init scale %s" % scale)
    sleep_delta = 1 / scale
    print("Delta %s" % sleep_delta)
    print("Period %s" % period)
    
    while check:
      msg_init_time = time.time()
      try:
        now = datetime.datetime.fromtimestamp(time.time())
        messages_on_queue = mq.current_messages
        DAT.write("%s %d %d\n" % (now.strftime("%H:%M:%S"), scale, messages_on_queue))
        DAT.flush()

        # Manda mensagem
        send_message(mq, service_counter, status_counter)
        status_counter = (status_counter + 1) % 4
        if status_counter == 0:
            service_counter = (service_counter + 1) % 8

        # calcula o tempo que deveria dormir descontando o tempo de envio
        msg_counter = msg_counter + 1
        now = time.time()
        sleep_time = sleep_delta - (now - msg_init_time)
                 
        if sleep_time > 0:
          time.sleep(sleep_time) 
        if  (now > init_time + period ):
          print(">>>>> Sent %s messages. Average of %s per sec" %(msg_counter,str(msg_counter/(now-init_time))))
          check = False
      except KeyboardInterrupt:
        DAT.close()
        print("User interrupted. Shutting down.")
        exit(0)
      except sysv_ipc.ExistentialError:
        print("Message queue does not exist for key")
        exit(1)
        
  DAT.close()
  

def send_message(mq, service_counter, status_counter):
    for item in test_service[service_counter]:
        data = test_service[service_counter][item][status_counter]
        for content in data:
            if service_counter < 7:
                message = 'riold122^%s^%s^%s' % (item, status_counter, data[content])
            else:
                message = 'riold122^%s' % (data[content])

    type = 13
    if service_counter == 7: # TODO if == 'host'
        type = 14
    try:
      mq.send(message, block=False, type=type)
    except sysv_ipc.BusyError:
	    print "Queue is full, ignoring"

if __name__ == "__main__":
    main()
